package common

import (
	"github.com/microcosm-cc/bluemonday"
	"github.com/russross/blackfriday"
	"strings"
	"net/http"
	"fmt"
	"os"
	"io"
)

/**
 *
 * @author  镜湖老杨
 * @date  2021/1/14 11:00 上午
 * @version 1.0
 */

type fileUtil struct{}

func (fileUtil) GetFileExtendsByType(fileType int) []string {
	var fileExtends []string
	switch fileType {
	case 1:
		fileExtends = append(fileExtends, "bmp", "jpg", "png", "tif", "gif", "jpeg", "webp")
		break
	case 2:
		fileExtends = append(fileExtends, "doc", "docx", "txt", "hlp", "wps", "rtf", "html", "pdf", "md", "sql", "css", "js", "vue", "java")
		break
	case 3:
		fileExtends = append(fileExtends, "avi", "mp4", "mpg", "mov", "swf")
		break
	case 4:
		fileExtends = append(fileExtends, "wav", "aif", "au", "mp3", "ram", "wma", "mmf", "amr", "aac", "flac")
		break
	case 5:
		fileExtends = append(fileExtends, "bmp", "jpg", "png", "tif", "gif", "jpeg", "webp",
			"doc", "docx", "txt", "hlp", "wps", "rtf", "html", "pdf", "md", "sql", "css", "js", "vue", "java",
			"avi", "mp4", "mpg", "mov", "swf",
			"wav", "aif", "au", "mp3", "ram", "wma", "mmf", "amr", "aac", "flac")
		break
	default:
		fileExtends = []string{}
		break
	}
	return fileExtends
}

func (fileUtil) MarkdownToHTML(md string) string {
	myHTMLFlags := 0 |
		blackfriday.HTML_USE_XHTML |
		blackfriday.HTML_USE_SMARTYPANTS |
		blackfriday.HTML_SMARTYPANTS_FRACTIONS |
		blackfriday.HTML_SMARTYPANTS_DASHES |
		blackfriday.HTML_SMARTYPANTS_LATEX_DASHES

	myExtensions := 0 |
		blackfriday.EXTENSION_NO_INTRA_EMPHASIS |
		blackfriday.EXTENSION_TABLES |
		blackfriday.EXTENSION_FENCED_CODE |
		blackfriday.EXTENSION_AUTOLINK |
		blackfriday.EXTENSION_STRIKETHROUGH |
		blackfriday.EXTENSION_SPACE_HEADERS |
		blackfriday.EXTENSION_HEADER_IDS |
		blackfriday.EXTENSION_BACKSLASH_LINE_BREAK |
		blackfriday.EXTENSION_DEFINITION_LISTS |
		blackfriday.EXTENSION_HARD_LINE_BREAK

	renderer := blackfriday.HtmlRenderer(myHTMLFlags, "", "")
	bytes := blackfriday.MarkdownOptions([]byte(md), renderer, blackfriday.Options{
		Extensions: myExtensions,
	})
	theHTML := string(bytes)
	return bluemonday.UGCPolicy().Sanitize(theHTML)
}

func (fileUtil) GetFileName(oraginalFilename string) string {
	var fileName string
	if oraginalFilename != "" && strings.Contains(oraginalFilename, ".") {
		s := strings.Split(oraginalFilename, ".")
		fileName = s[0]
	}
	return fileName
}

//创建名为dirName的文件夹，用于存放改分类的图片
func createDir(dirName string) string{
    dir := dirName

    //如果文件夹不存在，则创建
    _, err := os.Stat(dir)
    if err != nil {
        //os.Mkdir(dir, os.ModePerm)    //创建单个文件夹
        os.MkdirAll(dir, os.ModePerm)   //递归创建文件夹
    }
    return dir
}


func (fileUtil) SaveFile(finalUrl string, savePath string, dir string){

	createDir(dir)
	//判断文件是否存在，如果存在，说明已经下载了，直接return，下载下一张图片
    _, err := os.Stat(savePath)
    if err == nil {
        fmt.Printf("图片 [ %s ] 已下载\n", finalUrl)
        return
    }

    //创建文件：如果文件已存在，会将文件清空
    file, err := os.Create(savePath)
    if err != nil {
        fmt.Println("createFile error:", err.Error())
        return
    }
    defer file.Close()

    //读取url的信息，存入到文件
    resp, err := http.Get(finalUrl)
    if err != nil {
        fmt.Println("imageGet error:", err.Error())
        return
    }
    defer file.Close()

    buf := make([]byte, 4096)
    for {
        res, err2 := resp.Body.Read(buf)
        if res == 0{
            break
        }
        if err2 != nil && err2 != io.EOF {
            //err = err2
            return
        }
        //写入文件
        file.Write(buf[:res])
    }

    //循环结束，我们认为图片已经下载成功，控制台输出提示
    fmt.Printf("图片 [ %s ] 下载 [ %s ] 成功\n", finalUrl, savePath)

}

var FileUtil = &fileUtil{}
